package com.daocao.yfb.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import com.daocao.yfb.R;
import com.daocao.yfb.constant.IdCardBitmap;
import com.daocao.yfb.util.CameraManager;
import com.daocao.yfb.util.FileUtils;
import com.daocao.yfb.view.PreviewBorderView;

/*
* 拍照界面，身份证验证
* */
public class CameraActivity extends Activity
        implements Callback {
//    private static final String DEFAULT_NAME = "default.jpg";
//    private static final String DEFAULT_PATH = "/sdcard/";
//    private static final String DEFAULT_TYPE = "default";
    private ImageView back;
    private Bitmap bitmap2;
    private CameraManager cameraManager;
    private File file;
    private String fileName;
    private String filePath;
    private boolean hasSurface;
    private boolean isTake;
    private Intent mIntent;
    private LinearLayout mLinearLayout;
    private PreviewBorderView mPreviewBorderView;
    private SurfaceView mSurfaceView;
    private boolean safeToTakePicture = false;
    private ImageView take;
    private boolean toggleLight;
    private String type;
    private ImageView photo;

//    CameraCaptureSession.CaptureCallback



    Camera.PictureCallback myjpegCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(final byte[] data, Camera camera) {

            // 根据拍照所得的数据创建位图
//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inPreferredConfig = Bitmap.Config.ARGB_4444;
//            options.inPurgeable = true;// 允许可清除
//            options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果*/
//            final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
//                    data.length, options);
//            int height = bitmap.getHeight();
//            int width = bitmap.getWidth();
//
//
//            bitmap2 = ImageUtil.compressImage(Bitmap.createBitmap(bitmap, (width - height) / 2, height / 6, height, height * 2 / 3), 1000);
//            bitmap2 = ImageUtil.reduce(Bitmap.createBitmap(bitmap, (width - height) / 2, height / 6, height, height * 2 / 3), 1500, 1000, true);

//            Log.e("TAG------", "width:" + width + " height:" + height);
//            Log.e("TAG------", "x:" + (width - height) / 2 + " y:" + height / 6 + " width:" + height + " height:" + height * 2 / 3);
            // 创建一个位于SD卡上的文件
//            int size = 0;
//            size += bitmap.getByteCount();
//            Log.d("bitmap", size / 1024 + "");
//            int size1 = 0;
//            size1 += bitmap2.getByteCount();
//            Log.d("bitmap2", size1 / 1024 + "");
            isTake = true;
            back.setImageDrawable(ContextCompat.getDrawable(CameraActivity.this.getApplicationContext(), R.mipmap.error));
            take.setImageDrawable(ContextCompat.getDrawable(CameraActivity.this.getApplicationContext(), R.mipmap.tick));

//            设置图片的缩放大小
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, 750, 500);
            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            //            设置图片的缩放大小
            Bitmap resource = BitmapFactory.decodeByteArray(data, 0, data.length, options);
            bitmap2 = Bitmap.createBitmap(resource, (resource.getWidth() - resource.getHeight()) / 2, resource.getHeight() / 6, resource.getHeight(), resource.getHeight() * 2 / 3);
            if (!resource.isRecycled()) {
                resource.recycle();
            }

//            File path = new File(filePath);
//            if (!path.exists()) {
//                path.mkdirs();
//            }
//            file = new File(path, type + new Date().getTime() + fileName);
            clearCamera();
        }
    };

    public int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    private void initCamera() {
        this.cameraManager = new CameraManager(this, 1);
        SurfaceHolder localSurfaceHolder = ((SurfaceView) findViewById(R.id.surfaceview)).getHolder();
        if (this.hasSurface) {
            initCamera(localSurfaceHolder);
            return;
        }
        localSurfaceHolder.addCallback(this);
    }

    private void initCamera(SurfaceHolder paramSurfaceHolder) {
        if (paramSurfaceHolder == null)
            throw new IllegalStateException("No SurfaceHolder provided");
        if (this.cameraManager.isOpen()) {
            return;
        }
        try {
            this.cameraManager.openDriver(paramSurfaceHolder);
            this.cameraManager.startPreview();
            this.safeToTakePicture = true;
            return;
        } catch (Exception e) {
        }
    }

    private void initIntent() {
        this.mIntent = getIntent();
        this.filePath = this.mIntent.getStringExtra("path");
        this.fileName = this.mIntent.getStringExtra("name");
        this.type = this.mIntent.getStringExtra("type");
        if (this.filePath == null)
            this.filePath = "/sdcard/";
        if (this.fileName == null)
            this.fileName = "default.jpg";
        if (this.type == null)
            this.type = "default";
        Log.e("TAG", this.filePath + "/" + this.fileName + "_" + this.type);
    }

    private void initLayoutParams() {
        this.photo = (ImageView) findViewById(R.id.photo);
        this.take = ((ImageView) findViewById(R.id.take));
        this.back = ((ImageView) findViewById(R.id.back));
        this.take.setOnClickListener(new OnClickListener() {
            public void onClick(View paramAnonymousView) {

                if (CameraActivity.this.isTake) {

                    sendPhoto();

//                    isTake = true;
                } else {
                    if (safeToTakePicture) {
                        cameraManager.takePicture(null, null, myjpegCallback);
                        safeToTakePicture = false;
                        isTake = false;
                    }
                }
            }
        });
        this.back.setOnClickListener(new OnClickListener() {
            public void onClick(View paramAnonymousView) {
                if (CameraActivity.this.isTake) {
                    photo.setVisibility(View.GONE);
                    isTake = false;
                    CameraActivity.this.back.setImageDrawable(ContextCompat.getDrawable(CameraActivity.this.getApplicationContext(), R.mipmap.reback));
                    CameraActivity.this.take.setImageDrawable(ContextCompat.getDrawable(CameraActivity.this.getApplicationContext(), R.mipmap.camera));
                    CameraActivity.this.initCamera();
                } else
                    CameraActivity.this.finish();
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
            }
        });

        this.mPreviewBorderView = ((PreviewBorderView) findViewById(R.id.borderview));
        this.mSurfaceView = ((SurfaceView) findViewById(R.id.surfaceview));
    }

    private void sendPhoto() {
        FileOutputStream outStream = null;
        try {
            String path= FileUtils.getDiskCacheDir("xinbaobao");
            file = new File(path, type + new Date().getTime() + fileName);
//            打开指定文件对应的输出流
            outStream = new FileOutputStream(file);
            // 把位图输出到指定文件中
            bitmap2.compress(Bitmap.CompressFormat.JPEG,
                    40, outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        try {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            bitmap2.compress(Bitmap.CompressFormat.PNG, 70, baos);
//            byte[] bitmapByte = baos.toByteArray();
//            baos.close();
        IdCardBitmap.bitmap = bitmap2;
        mIntent = getIntent();
//        Bundle localBundle = new Bundle();
//        localBundle.putString("path", CameraActivity.this.file.getAbsolutePath());
//        localBundle.putString("type", CameraActivity.this.type);
//        mIntent.putExtras(localBundle);
//        Log.e("TAG", file.getAbsolutePath() + "类型：" + type);
//            mIntent.putExtra("bitmap", bitmapByte);
        setResult(-1, mIntent);
        finish();
        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        requestWindowFeature(1);
        getWindow().setFlags(1024, 1024);
        setContentView(R.layout.camera_activity);
        initIntent();
        initLayoutParams();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearCamera();
    }


    private void clearCamera() {
        this.cameraManager.stopPreview();
        this.cameraManager.closeDriver();
        if (!this.hasSurface)
            ((SurfaceView) findViewById(R.id.surfaceview)).getHolder().removeCallback(this);
    }


    public void surfaceChanged(SurfaceHolder paramSurfaceHolder, int paramInt1, int paramInt2, int paramInt3) {
    }

    public void surfaceCreated(SurfaceHolder paramSurfaceHolder) {
        if (!this.hasSurface) {
            this.hasSurface = true;
            initCamera(paramSurfaceHolder);
        }
    }

    public void surfaceDestroyed(SurfaceHolder paramSurfaceHolder) {
        this.hasSurface = false;
    }

    @Override
    protected void onResume() {
        super.onResume();

        initCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        clearCamera();
    }
}
